<template>
	<view class="">
		<button v-if="!vuex_hasLogin" @click.self="button_click" class="u-reset-button">
			<slot></slot>
		</button>
		<button v-if="vuex_hasLogin" :open-type="open_type" @click.self="button_click" class="u-reset-button">
			<slot></slot>
		</button>
		<u-toast ref="uToast" :icon='false' />
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		name: "LoginButton",
		data() {
			return {

			}
		},
		props: {
			open_type: {
				type: [String],
				default: '',
			},
			item: {
				type: [Array, Object, String, Number],
				default: ''
			}
		},
		methods: {
			async button_click(val) {
				if (!this.vuex_hasLogin) {
					let user_info = await uni.getUserProfile({
						provider: 'weixin',
						desc: '用于完善会员资料',
					});

					let encryptedData;
					let iv;
					let code;

					if (user_info[0]) {
						this.$refs.uToast.show({
							title: "未获得您的授权",
							type: 'error',
							position: 'bottom',
						});
						return false;
					};

					if (user_info[1]) {
						encryptedData = user_info[1].encryptedData;
						iv = user_info[1].iv;

						let login_info = await uni.login({
							provider: 'weixin',
						});
						if (login_info[1]) {
							code = login_info[1].code
						} else {
							this.$refs.uToast.show({
								title: "获取用户码错误",
								type: 'error',
								position: 'bottom',
							});
							return false ;
						}
					};
					let model = {
						encryptedData ,
						iv ,
						code ,
					}
					if(this.vuex_sale) {
						model.sale_id = this.vuex_sale ;
					}

					this.$u.api.login(model).then(res => {
						if (res.code == 1) {
							this.$u.vuex('vuex_user', res.info);
							this.$u.vuex('vuex_hasLogin', true);
							this.$u.vuex('vuex_token', res.info.token);
							this.$u.vuex('vuex_sale' , '' ) ;
							// 登陆成功之后请求用户详情信息
							this.getUserInfo() ;
						}else {
							this.$refs.uToast.show({
								title: "登陆失败,请重新登陆.",
								type: 'error',
								position: 'bottom',
								icon : false ,
							});
						}
					})
				} else {
					this.$emit('click', this.item)
				};
			},
			
			// 获取用户信息
			getUserInfo() {
				if (this.vuex_hasLogin) {
					this.$u.api.getUserInfo({}).then(res => {
						this.$u.vuex('vuex_userInfo' , res.info) ;
						this.$isResolve();
					})
				}
			
			},
		},
		computed: {
			...mapState({
				vuex_user: state => state.vuex_user,
				vuex_hasLogin: state => state.vuex_hasLogin,
			})
		}
	}
</script>

<style>
	.u-reset-button{
		/* background-color: red;
		height: 150rpx; */
	}
</style>
